package com.weiyuwqj.api.tool;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.weiyuwqj.api.util.JsonUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Copyright 2015-2019 Yunfucloud technology co., Ltd.
 * Created by fuxx on 16/1/7.
 */
public class QiniuUpload {

    public static String uploadQiniu(String path,String filename){
        System.out.println(path);
        String url="http://onlyvy1nf.bkt.clouddn.com/";
        String ACCESS_KEY="kAqVsNW7U3BCJ9aS6gY_kqGDb_t4_KxqdwFTkMnu";
        String SECRET_KEY="DCWiROInykqBPRoBtvxe6Oo7eyKIn49voDmWXJKm";
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String token=auth.uploadToken("tiange", null, 3600, new StringMap()
                .put("scope","tiange:"+filename)
                .put("callbackBody", "key=$(key)&hash=$(etag)"));
        UploadManager uploadManager = new UploadManager();

        try {
            Response res = uploadManager.put(path, filename, token);
            Map<String,Object> map= JsonUtils.json2Map(res.bodyString());
            System.out.println(res);
            System.out.println(res.bodyString());
            if(res.isOK()){
                Object o=map.get("key");
                if(o==null) return null;
                return url+o.toString();
            }else {
                return null;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            System.out.println(r);
//            try {
//                System.out.println(r.bodyString());
//            } catch (QiniuException e1) {
//                //ignore
//            }
        }
        return null;

    }

    public static Map fileUploadHandle(MultipartFile file,String serverDir,String targetDir){
        HashMap<String,Object> ret=new HashMap<String, Object>();
        File dir=new File(serverDir+"upload");
        String fileName=file.getOriginalFilename();
        String ext=fileName.substring(fileName.lastIndexOf("."));
        String url="/upload/"+new Date().getTime()+ext;
        if(!dir.exists()){
            dir.mkdir();
        }
        String fullPath="";
        String newFileName=new Date().getTime()+ext;
        if(targetDir!=null&&targetDir.isEmpty()){
            newFileName=targetDir+"/"+newFileName;
        }
        if (!file.isEmpty()) {
            try {
                fullPath= serverDir+"upload/"+ newFileName;
                //拿到输出流，同时重命名上传的文件
                FileOutputStream os = new FileOutputStream(fullPath);
                //拿到上传文件的输入流
                InputStream in = (InputStream) file.getInputStream();
                //以写字节的方式写文件
                int b = 0;
                while((b=in.read()) != -1){
                    os.write(b);
                }
                os.flush();
                os.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("上传出错");
            }
            QiniuUpload upload=new QiniuUpload();
            url=upload.uploadQiniu(fullPath,newFileName);
            ret.put("state","success");
            ret.put("url",url);

        } else {
            ret.put("state","fail");
        }
        ret.put("statusText","sdfsdfds");
        return ret;
    }

}

